<?php
/**
 * Created by PhpStorm.
 * User: qishengqiang
 * Date: 2022-06-02
 * Time: 15:10
 */

namespace app\applet\controller;


use app\applet\BaseController;

class WelfareController extends BaseController
{
    /**
     * @return \think\response\Json
     */
    public function linkersAction()
    {
        try {
            //1. 轮播图
            $broadcasts = $this->app->broadcastService->getBroadcastByPositionId(3, $this->appletId);

            $data['broadcast'] = count($broadcasts)?$broadcasts:[];

            //2. 推广图
            $broadcasts = $this->app->broadcastService->getBroadcastByPositionId(4, $this->appletId);

            $data['popularize'] = count($broadcasts)?$broadcasts[0]:[];

            //2. 推广链接
            $linkers = $this->app->linkerService->getAll($this->appletId);
            $data['linkers'] = $linkers;

            return json()->data(['code' => 200, 'msg' => '查询成功','data' => $data]);
        }catch(\Exception $e){
            return json()->data(['code'=>$e->getCode(),"msg"=>$e->getMessage()]);
        }
    }

    /**
     * @return \think\response\Json
     */
    public function goodsAction()
    {
        try {

            $params['where'][] = ['status', '=', 1];
            $params['order'] = ['sort' => 'desc'];
            $goods = $this->app->goodsService->getLists($params, $this->page, $this->pagesize);

            $data['lists'] = [];
            if (count($goods)) {
                foreach ($goods as $good) {
                    $data['lists'][] = [
                        'goodsId' => $good->goodsId,
                        'goodsName' => $good->goodsName,
                        'categoryId' => $good->categoryId,
                        'thumb' => $good->thumb,
                        'marketPrice' => $good->marketPrice,
                        'credit' => $good->credit,
                        'stock' => $good->stock,
                        'saleCount' => $good->viewCount,
                    ];
                }
            }

            $data['totalInfo'] = $this->app->utilService->getMeta($goods);


            return json()->data(['code' => 200, 'msg' => '查询成功','data'=>$data]);
        }catch(\Exception $e){
            return json()->data(['code'=>$e->getCode(),"msg"=>$e->getMessage(), 'data' => []]);
        }
    }

    public function clickAction($id)
    {
        try {
            if (!$this->user) {
                throw new \Exception('请先登录', 401);
            }

            $linker = $this->app->linkerService->getDetail($id);

            $remark = '点击'.$linker->linkerName.',获取'.$linker->clickCredit.'积分';
            $this->app->userCreditService->add($this->user, $linker->clickCredit, $remark);


            return json()->data(['code' => 200, 'msg' => '操作成功','data'=>[]]);
        }catch(\Exception $e){
            return json()->data(['code'=>$e->getCode(),"msg"=>$e->getMessage(), 'data' => []]);
        }
    }
}